package com.xiu.travel.security.controller;

import com.xiu.travel.entity.UmsMember;
import com.xiu.travel.other.UmsMemberDTO;
import com.xiu.travel.security.pojo.dto.SmsLoginDTO;
import com.xiu.travel.security.service.UmsMemberService;
import com.xiu.travel.util.MailUtil;
import com.xiu.travel.util.RedisUtil;
import com.xiu.travel.util.ServletUtils;
import com.xiu.travel.util.api.CommonResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@Tag(name = "登陆接口", description = "登陆接口")
@RequestMapping("/admin/open")
@Slf4j
public class LoginController {
    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 会员登陆
     *
     * @param username 用户名
     * @param password 吗
     * @return r result
     * @author qianl
     */
    @GetMapping("passWord")
    @Operation(summary = "用户名密码登录")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> login(@RequestParam("username") @Parameter(name = "username", description = "用户名", required = true) String username, @RequestParam("password") @Parameter(name = "password", description = "密码", required = true) String password) {
        CommonResult<String> result = CommonResult.success("");
        var verify = redisUtil.getCacheObject("verify:" + username.toLowerCase()).toString();
        if (!verify.equals("")) {
            final var realUser = umsMemberService.getOne(new LambdaQueryWrapper<UmsMember>().eq(UmsMember::getPhone, username).or().eq(UmsMember::getMail, username));
            if (Objects.isNull(realUser)) {
                umsMemberService.saveOne(new UmsMemberDTO().setNickname(username).setUsername(username).setMail(username).setPassword("$2a$10$D/recLnj0/vi9v71RwHW3u0tiel6Ms0vzHkCA/wuQwDR64TtcUc8e"));
                result = umsMemberService.loadUserByUsername(username, "666666");
            }else {
                result = umsMemberService.loadUserByMail(realUser.getUsername(), realUser.getPassword());
            }
        } else {
            result = umsMemberService.loadUserByUsername(username, password);
        }
        redisUtil.deleteObject("verify:" + username);
        Objects.requireNonNull(ServletUtils.getResponse()).setHeader("Set-Cookie", "token=" + result.getData() + "; Domain=.clubm.top; Path=/;SameSite=None;Secure;");
        return result;
    }

    /**
     * @param smsLoginDTO
     * @return r result
     * @author qianl
     */
    @PostMapping("sms")
    @Operation(summary = "短信验证登录")
    public CommonResult<String> loginBySms(@RequestBody SmsLoginDTO smsLoginDTO) {

        CommonResult<String> stringCommonResult = umsMemberService.loginBySms(smsLoginDTO.getPhone(), smsLoginDTO.getCode(), smsLoginDTO.getPassword());
        Objects.requireNonNull(ServletUtils.getResponse()).setHeader("Set-Cookie", "token=" + stringCommonResult.getData() + "; Domain=.clubm.top; Path=/")

        ;
        return stringCommonResult;
    }

    @GetMapping("getSms/{phone}")
    @Operation(summary = "通过手机号获取短信验证码，短信有效期为半小时")
    public CommonResult<String> getSms(@PathVariable("phone") String phone) throws Exception {
        return umsMemberService.getSms(phone);
    }

    @GetMapping("getMall/{mail}")
    @Operation(summary = "获取邮箱验证码")
    public CommonResult<String> getMall(@PathVariable("mail") @Parameter(description = "接受邮箱", required = true) String mail) throws Exception {
        var i = Math.abs(UUID.randomUUID().hashCode()) % 10000;
        while (redisUtil.getCacheObject("verify:" + mail.toLowerCase()).toString().equals("")) {
            redisUtil.setCacheObject("verify:" + mail.toLowerCase(), i, 30L, TimeUnit.MINUTES);
        }
        mailUtil.sendSimpleMail("2502203399@qq.com", mail.toLowerCase(), "2502203399@qq.com", "你的验证码是：" + redisUtil.getCacheObject("verify:" + mail.toLowerCase()).toString() + "有效期30分钟");
        return CommonResult.success("");
    }

    /**
     * 登陆
     *
     * @param phone    用户名
     * @param password 吗
     * @return r result
     * @author qianl
     */
    @GetMapping("phone")
    @Operation(summary = "手机号密码登录")
    public CommonResult<String> loginByPhoneNumber(@RequestParam("phone") @Parameter(name = "phone", description = "手机号") String phone, @RequestParam("password") @Parameter(name = "password", description = "密码") String password) {
        HttpServletResponse response = ServletUtils.getResponse();
        UmsMember umsMember = umsMemberService.getOne(new LambdaQueryWrapper<UmsMember>().eq(UmsMember::getPhone, phone));
        if (ObjectUtils.isEmpty(umsMember)) {
            return CommonResult.failed("手机号或密码错误");
        }
        log.info("umsMember==={}", umsMember);
        CommonResult<String> stringCommonResult = umsMemberService.loadUserByUsername(umsMember.getUsername(), password);
        log.info("umsMember.getUsername()==={}", umsMember.getUsername());

        Cookie cookie = new Cookie("token", stringCommonResult.getData());
        cookie.setPath("/");
        cookie.setSecure(false);
        cookie.setVersion(2);
        cookie.setDomain("clubm.top");
        cookie.setMaxAge(6000000);
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
        Objects.requireNonNull(ServletUtils.getResponse()).setHeader("Set-Cookie", "token=" + stringCommonResult.getData() + "; Domain=.clubm.top; Path=/");

        return stringCommonResult;
    }

    /**
     * 登陆
     *
     * @return r result
     * @author qianl
     */
    @GetMapping("/login/wechat")
    @Operation(summary = "小程序微信Code一键登录")
    public CommonResult<String> loginByWeChat(@RequestParam("openIdCode") @Parameter(name = "openIdCode", description = "微信openIdCode") String openIdCode, @RequestParam("phoneCode") @Parameter(name = "phoneCode", description = "微信phoneCode") String phoneCode) {

        CommonResult<String> stringCommonResult = umsMemberService.loginByWeChat(openIdCode, phoneCode);
        ServletUtils.getResponse().setHeader("Set-Cookie", "token=" + stringCommonResult.getData() + "; Domain=.clubm.top; Path=/;SameSite=None;Secure;");
        return stringCommonResult;
    }

    /**
     * 登陆
     *
     * @return r result
     * @author qianl
     */
    @GetMapping("/login/wechat/zjh")
    @Operation(summary = "小程序微信Code一键登录")
    public CommonResult<String> loginByWeChatToZJH(@RequestParam("openIdCode") @Parameter(name = "openIdCode", description = "微信openIdCode") String openIdCode, @RequestParam("phoneCode") @Parameter(name = "phoneCode", description = "微信phoneCode") String phoneCode) throws Exception {

        CommonResult<String> stringCommonResult = umsMemberService.loginByWeChatToZJH(openIdCode, phoneCode);
        ServletUtils.getResponse().setHeader("Set-Cookie", "token=" + stringCommonResult.getData() + "; Domain=.clubm.top; Path=/;SameSite=None;Secure;");
        return stringCommonResult;
    }


}
